package com.bj58.mis.apm.client.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class PropsUtil {
    private static Logger logger = LoggerFactory.getLogger(PropsUtil.class);

    public static void printApmProperties(Properties props, String title) {
        StringBuilder logStr = new StringBuilder();
        logStr.append("\n==========="+title+"==========\n");
        List<String> propNameList = new ArrayList<>(props.stringPropertyNames());
        Collections.sort(propNameList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        for(String key : propNameList){
            logStr.append(key+"="+props.getProperty(key)+"\n");
        }
        logStr.append("=======================================\n");
        logger.debug(logStr.toString());
    }

    public static void loadProperties(Properties props, String configPath){
        Properties properties = loadProperties(configPath);
        for(String key : properties.stringPropertyNames()){
            props.setProperty(key, properties.getProperty(key));
        }
    }
    public static Properties loadProperties(String configPath){
        logger.debug("config absolute path : " + PropsUtil.class.getClassLoader().getResource(configPath));
        Properties props = new Properties();
        InputStream is = PropsUtil.class.getClassLoader().getResourceAsStream(configPath);
        try{
            props.load(is);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        printApmProperties(props, configPath);
        return props;
    }
}
